<?php
declare (strict_types=1);

namespace app\admin\controller\iot;

use app\admin\model\advertiser\AdvertiserThird;
use app\admin\model\iot\AdvertiserTaskDevice;
use app\admin\model\iot\ScanBagStrategy as ScanBagStrategyModel;
use app\admin\model\iot\ScanBagStrategyDevice;
use app\admin\model\iot\ScanBagWay;
use app\admin\model\iot\ScanBagWayDevice;
use app\admin\validates\ScanBagStrategyValidate;
use app\admin\validates\ScanBagValidate;
use app\BaseController;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\exception\ValidateException;
use think\facade\Filesystem;
use think\facade\Request;
use think\response\Json;
use upload\ImgUpload;

/**
 * 取袋策略配置中心
 */
class ScanBagStrategy extends BaseController
{



    /**
     * 取袋策略配置列表
     * @return Json
     */
    public function list(): Json
    {
        $version = Request::param('version/s', 'V1');
        $where[] = ['key', 'like', $version . '%'];
        $where= [];
        $data = ScanBagStrategyModel::getList($where);
        return jsonReturn(1, $data);
    }

    /**
     * 取袋策略新增
     * @return Json
     */
    public function add(): Json
    {
        $params['key'] = Request::param('key/s');
        $params['name'] = Request::param('name/s');
        $params['type'] = Request::param('type/d');
        $params['first'] = Request::param('first/d');
        $params['second'] = Request::param('second/d');
        $params['third'] = Request::param('third/d');
        $params['remark'] = Request::param('remark/s');
        //数据验证
        try {
            validate(ScanBagStrategyValidate::class)->scene('add')->check($params);
        } catch (ValidateException $e) {
            return jsonReturn(0, [], $e->getError());
        }

        $res = (new ScanBagStrategyModel())->save($params);
        if ($res) {
            return jsonReturn(1, [], '新增成功');
        }
        return jsonReturn(0, [], '新增失败');
    }

    /**
     * 取袋路径配置编辑
     * @return Json
     */
    public function edit(): Json
    {
        $params['id'] = Request::param('id/d');
        $params['key'] = Request::param('key/s');
        $params['name'] = Request::param('name/s');
        $params['type'] = Request::param('type/d');
        $params['first'] = Request::param('first/d');
        $params['second'] = Request::param('second/d');
        $params['third'] = Request::param('third/d');
        $params['remark'] = Request::param('remark/s');
        //数据验证
        try {
            validate(ScanBagStrategyValidate::class)->scene('edit')->check($params);
        } catch (ValidateException $e) {
            return jsonReturn(0, [], $e->getError());
        }
        //获取当前模型
        $Model = ScanBagStrategyModel::where(['id' => $params['id']])->find();
        if (!$Model) {
            return jsonReturn(0, [], '对象不存在');
        }
        $res = $Model->save($params);
        if ($res) {
            return jsonReturn(1, [], '修改成功');
        }
        return jsonReturn(0, [], '修改失败');
    }

    ################################### 设备绑定路径 #################################

    /**
     * 出袋策略设备列表
     * @return Json
     */
    public function deviceList(): Json
    {
        $params['key'] = Request::param('key/s','');
        $params['page'] = Request::param('page/d', 1);
        $params['limit'] = Request::param('limit/d', 10);
        $where =[];
        if($params['key']){
            $where['key']=$params['key'];
        }
        $data = ScanBagStrategyDevice::getList($where, $params['page'], $params['limit'], 'id desc');
        return jsonReturn(1, $data);
    }



    /**
     * 出袋策略添加设备
     * @return Json
     */
    public function addDevice(): Json
    {
        $params['key'] = Request::param('key/s', '');
        $params['mac_ids'] = Request::param('mac_ids/a', []);
        $params['remark'] = Request::param('remark/s', '');
        //数据验证
        if (!$params['mac_ids']) {
            return jsonReturn(0, [], 'mac_ids参数错误');
        }
        //获取当前模型
        $mac_ids = $data = [];
        foreach ($params['mac_ids'] as $k => $mac_id) {
            //判断是否重复
            if (in_array($mac_id, $mac_ids)) {
                continue;
            } else {
                $mac_ids[] = $mac_id;
            }
            //删除当前设备
            ScanBagStrategyDevice::deleteData(['mac_id' => $mac_id], true);
            //修改数据库记录
            $data[$k]['key'] = $params['key'];
            $data[$k]['mac_id'] = $mac_id;
            $data[$k]['remark'] = $params['remark'];
            $data[$k]['update_time'] = time();
        }
        $model = new ScanBagStrategyDevice();
        $model->saveAll(array_merge($data));
        return jsonReturn(1, [], '添加成功');
    }

    /**
     * 出袋策略导入设备
     * @return Json
     */
    public function importDevice(): Json
    {
        $key = Request::param('key/s', '');
        $file = request()->file('xlsx');
        if (!$file) {
            return jsonReturn(0, []);
        }
        //数据验证
        validate(['file' => [
            'fileSize' => 16388608,
            'fileExt' => 'xls,xlsx',
        ]])->check(['file' => $file]);
        //保存文件
        $savename = Filesystem::putFile('', $file);
        //获取文件完整路径
        $savename = Filesystem::path($savename);
        $reader = IOFactory::createReader('Xlsx');
        $reader->setReadDataOnly(TRUE);
        //载入excel表格
        $spreadsheet = $reader->load($savename);
        $worksheet = $spreadsheet->getActiveSheet();
        //总行数
        $highestRow = $worksheet->getHighestRow();
        //总列数
        $highestColumn = $worksheet->getHighestColumn();
        $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn);
        //判断是否有数据
        $lines = $highestRow - 1;
        if ($lines <= 0) {
            return jsonReturn(0, [], 'Excel表格中没有数据');
        }
        //循环获取行数据
        $mac_ids = $data = [];
        for ($row = 2; $row <= $highestRow; ++$row) {
            //设备地址
            $mac_id = trim($worksheet->getCellByColumnAndRow(1, $row)->getValue());
            if (in_array($mac_id, $mac_ids)) {
                continue;
            } else {
                $mac_ids[] = $mac_id;
            }
            //需要保存数据的数据
            $data[$row]['key'] = $key;
            $data[$row]['mac_id'] = $mac_id;
            //备注
            $shop = trim($worksheet->getCellByColumnAndRow(10, $row)->getValue());
            $address = trim($worksheet->getCellByColumnAndRow(11, $row)->getValue());
            $data[$row]['remark'] = $shop . '-' . $address;
            $data[$row]['update_time'] = time();
            //删除当前设备
            ScanBagWayDevice::deleteData(['mac_id' => $mac_id], true);
        }
        $model = new ScanBagStrategyDevice();
        $model->saveAll(array_merge($data));
        return jsonReturn(1, [], '导入成功');
    }


    /**
     * 出袋策略删除设备
     * @return Json
     */
    public function delDevice(): Json
    {
        $params['mac_ids'] = Request::param('mac_ids/a', []);
        //数据验证
        if (!$params['mac_ids']) {
            return jsonReturn(0, [], 'mac_ids参数错误');
        }
        //获取当前模型
        foreach ($params['mac_ids'] as $v) {
            ScanBagStrategyDevice::deleteData(['mac_id' => $v], true);
        }
        return jsonReturn(1, [], '删除成功');
    }



}
